<template>
  <div style="width: 50%; margin: 0 auto">
    <a-form
      :model="formState"
      name="basic"
      :label-col="{ span: 8 }"
      :wrapper-col="{ span: 16 }"
      autocomplete="off"
      @finish="onFinish"
      @finishFailed="onFinishFailed"
    >
      <a-form-item
        label="昵称"
        name="username"
        :rules="[{ required: true, message: 'Please input your username!' }]"
      >
        <a-input v-model:value="formState.username">
          <template #prefix>
            <UserOutlined class="site-form-item-icon" />
          </template>
        </a-input>
      </a-form-item>
      <a-form-item
        label="账号"
        name="email"
        :rules="[{ required: true, message: 'Please input your email!' }]"
      >
        <a-input v-model:value="formState.email">
          <template #prefix>
            <MobileOutlined class="site-form-item-icon" />
          </template>
        </a-input>
      </a-form-item>

      <a-form-item
        label="密码"
        name="password"
        :rules="[{ required: true, message: 'Please input your password!' }]"
      >
        <a-input-password v-model:value="formState.password">
          <template #prefix>
            <LockOutlined class="site-form-item-icon" />
          </template>
        </a-input-password>
      </a-form-item>

      <a-form-item
        label="确认密码"
        name="password2"
        :rules="[{ required: true, message: 'Please input your password!' }]"
      >
        <a-input-password v-model:value="formState.password2">
          <template #prefix>
            <LockOutlined class="site-form-item-icon" />
          </template>
        </a-input-password>
      </a-form-item>

      <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
        <a-flex justify="center" align="center">
          <a-button type="primary" html-type="submit">注册</a-button>
        </a-flex>
      </a-form-item>
    </a-form>
  </div>
</template>
<script lang="ts" setup>
import { reactive, h } from 'vue'
import { useRouter } from 'vue-router'
import { createUser } from '@/http/user'
import { UserOutlined, LockOutlined, MobileOutlined } from '@ant-design/icons-vue'
import { Modal } from 'ant-design-vue'

const router = useRouter()

interface FormState {
  username: string
  email: string
  password: string
  password2: string
}

const formState = reactive<FormState>({
  username: '',
  email: '',
  password: '',
  password2: '',
})
const success = () => {
  Modal.success({
    title: '注册成功',
    content: h('div', {}, [h('p', '您的账号已成功注册！'), h('p', '请登录以继续使用我们的服务。')]),
    onOk() {
      router.replace('/login')
    },
  })
}
const onFinish = (values: any) => {
  createUser(values).then((res) => {
    success()
  })
}

const onFinishFailed = (errorInfo: any) => {
  console.log('Failed:', errorInfo)
}
</script>
